<!-- 添加采购单 -->
<template>
  <div>
    <!-- 采购单管理页面 添加采购单/查看采购单顶部区域，查看携带interId则不显示查看条件-->
    <cus-search v-if="!this.$route.query.interId" style="padding-bottom: 0;">
      <cus-search-item>
        <Form :model="searchForm" @keydown.native.enter.prevent="onInit">
          <FormItem
            label="供应日期"
            :label-width="95"
            class="mr_48 mb_20"
            prop="supplyDate"
            :rules="{
              required: true,
              message: '供应日期不能为空',
              trigger: 'change',
            }"
          >
            <DatePicker
              type="date"
              :value="searchForm.supplyDate"
              format="yyyy-MM-dd"
              @on-change="sDateChange"
              placeholder="请选择供应日期"
              style="width: 200px"
            />
          </FormItem>
          <FormItem label="供应商" :label-width="100" class="mr_48 mb_20">
            <Select
              v-model="searchForm.supplyId"
              style="width: 200px"
            >
              <Option
                v-for="item in supplyTree"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
          <cusButton class="mr_20 mb_20" type="primary" @onClick="onSave()"
            >保存</cusButton
          >
          <cusButton
            class="mr_20 mb_20"
            @onClick="onAdd()"
            style="background: #08b5ad; color: #ffffff"
            >添加明细</cusButton
          >
        </Form>
      </cus-search-item>
    </cus-search>
    <cus-card class="cus_cardBox" :showTitle="false">
      <div id="printContent">
        <!-- 采购单管理页面 -查看采购单，查看携带interId则显示 新增按钮，供应商名称，单号条件-->
        <div class="contentBox" v-if="this.$route.query.interId">
          <div class="contentBox-itemRightBox">
            <div class="dl" style="width: 30%">
              <h3 class="mr_10">供应商名称:</h3>
              <span class="mr_10">{{ this.$route.query.supplyName }}</span>
            </div>
            <div class="dl" style="width: 30%">
              <h3 class="mr_10">采购单号:</h3>
              <span class="mr_10">{{ this.$route.query.billNo }}</span>
            </div>
            <div class="dl" style="width: 30%">
              <h3 class="mr_10">供应时间:</h3>
              <span class="mr_10">{{
                new Date(this.$route.query.deliveDate).Format("yyyy-MM-dd")
              }}</span>
              <span class="mr_20">{{ this.$route.query.week }}</span>
            </div>
          </div>
          <cusButton
            class="mb_20"
            type="primary"
            v-if="this.$route.query.status != 1"
            @onClick="onAdd()"
            style="width: 150px"
            >新增</cusButton
          >
          <!-- <cusButton
          class="mr_48 mb_20"
          type="error"
          @onClick="onPrint()"
          style="width: 150px"
          >打印</cusButton
        > -->
        </div>
        <cusTable
          border
          :loading="form.loading"
          :columns="columns"
          :data="data"
          :size="vuex_config.tableSize"
          :bottomClass="['cus-page','cus_operBox']"
          highlight-row
        >
          <template slot-scope="{ row, index }" slot="operation">
            <div class="flex">
              <cus-button
                type="text"
                size="small"
                :style="{ color: '#1E6FFF' }"
                style="padding: 0 5px"
                v-if="$route.query.status != 1"
                @onClick="onEdit(row)"
              >
                <Icon
                  type="md-color-filter"
                  size="4"
                  style="margin: 2px 5px 0 0"
                />
                <span>修改</span>
              </cus-button>
              <cus-button
                type="text"
                size="small"
                v-if="$route.query.status != 1"
                :style="{ color: '#FF4746' }"
                style="padding: 0 5px"
                @onClick="onDelete(row)"
              >
                <Icon type="md-trash" size="4" style="margin: 2px 5px 0 0" />
                <span>删除</span>
              </cus-button>
            </div>
          </template>
        </cusTable>
      </div>
      <div class="cus_page">
        <cus-page
          :data="pages"
          class="mt_20"
          @pageChange="postApiPurchasingPoorderdtllistApi()"
        ></cus-page>
      </div>
    </cus-card>
    <!--底部返回-->
    <!-- <div class="operBox" style="z-index: 1001;width: calc(100% - 250px)">
      <Button type="error" class="mr_20" @click="onReturn">返回</Button>
    </div> -->
    <div class="cus_operBox" style="z-index: 1001;width: calc(100% - 250px)">
      <Button type="error" class="mr_20" @click="onReturn">返回</Button>
    </div>
    <!--修改采购单采购量-->
    <Modal v-model="show" width="400" title="修改采购食材">
      <Form
        :model="form"
        :label-width="120"
        ref="formValidate"
        @keydown.native.enter.prevent="onInit"
      >
        <FormItem label="食品名称">
          <Input
            v-model="form.productName"
            disabled
            placeholder="请输入食品名称"
          />
        </FormItem>
        <FormItem label="食材规格">
          <Input
            v-model="form.specifications"
            disabled
            placeholder="请输入规格"
          />
        </FormItem>
        <FormItem label="采购数量">
          <!-- 此处根据 weightFlag是否称重出入库字段判断是取数量还是重量-->
          <!-- <InputNumber
            :max="10000"
            :min="0"
            v-if="weightFlag"
            v-model="form.weight"
            @input="floatInput"
            style="width: 185px"
          /> -->
          <InputNumber
            :max="10000"
            :min="0"
            v-model="form.packagingQty"
             :active-change="false"
            :precision ='form.weightFlag ? 2 : 0'
            @input="floatInput"
            style="width: 185px"
          />
        </FormItem>
        <FormItem label="价格(元)">
          <Input v-model="form.packagingPrice" disabled placeholder="请输入食材价格" />
        </FormItem>
        <FormItem label="金额(元)">
          <Input v-model="sum" placeholder="0" disabled style="width: 185px" />
        </FormItem>
      </Form>
      <div slot="footer">
        <slot name="footer">
          <div class="modal-footer">
            <cus-button type="primary" size="small" @onClick="show = false"
              >取消</cus-button
            >
            <cus-button type="primary" size="small" @onClick="ok"
              >确认</cus-button
            >
          </div>
        </slot>
      </div>
    </Modal>
    <!--添加明细-->
    <addPurchaseDetails ref="addPurchaseDetails"></addPurchaseDetails>
  </div>
</template>
<script>
import {
  postApiPurchasingPoorderdtllist,
  getApiPurchasingSupplierName,
  postApiPurchasingManualSavePoOrder,
  postApiPurchasingUpdatePoOrderDtl,
  postApiPurchasingDeletePoOrderDtlById,
} from "@/api/business/manager";
import addPurchaseDetails from "./addPurchaseDetails.vue";
export default {
  components: { addPurchaseDetails },
  data() {
    return {
      form: {
        id: "",
        supplyId : null, //供应商id
        purchasingPlanId: "", //采购id
        supplyDate: null, //select选择供应时间
        productName: null, //食材名称
        specifications: "", //食材规格
        packagingQty: null, //采购数量
        // weight: null, //采购重量
        packagingPrice: null, //食材价格
        amount: null, //食材金额
        supplyTime: null, //修改提示供应时间
        loading: false,
      },
      searchForm: {
        supplyDate: null, //select选择供应时间
        supplyId: null, //供应商id
      },
      supplyTree: [], //供应商名称tree数据
      ruleValidate: {},
      // 表头
      columns: [
        {
          title: "序号",
          type: "index",
          align: "center",
          width: 70,
        },
        {
          title: "原料名称",
          key: "materialName",
          align: "center",
          minWidth: 125,
        },
        // {
        //   title: "采购重量",
        //   key: "weight",
        //   align: "center",
        //   minWidth: 125,
        // },
        {
          title: "商品名称",
          key: "productName",
          align: "center",
          minWidth: 125,
        },
        {
          title: "商品计量单位",
          key: "packagingUtil",
          align: "center",
          minWidth: 125,
        },
        {
          title: "采购数量",
          key: "packagingQty",
          align: "center",
          minWidth: 125,
        },
        {
          title: "价格(元)",
          key: "packagingPrice",
          align: "center",
          minWidth: 125,
        },
        {
          title: "金额(元)",
          key: "amount",
          align: "center",
          minWidth: 125,
        },
        {
          title: "创建时间",
          key: "createTime",
          align: "center",
          minWidth: 175,
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                {
                  style: {},
                },
                new Date(params.row.createTime).Format("yyyy-MM-dd")
              ),
            ]);
          },
        },
        {
          title: "供应时间",
          key: "supplyTime",
          minWidth: 175,
          align: "center",
        },
        {
          title: "操作",
          fixed: "right", // 右侧固定
          slot: "operation",
          align: "center",
          width: 175,
        },
      ],
      data: [], // 表格列表
      show: false, //修改模态框
      // weightFlag: false, //用于修改模态框下采购数量时,true称重入库,false件,箱,袋入库
      amountSum: null,
      // 分页
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      tableHeight: 0,
      supplyId: null,
    };
  },
  mounted() {
    setTimeout(() => {
      this.tableHeight = window.innerHeight - 370; // 表格自适应高度
    }, 100);
    window.addEventListener("resize", this.tableHeightChange, true);
    this.postApiPurchasingPoorderdtllistApi();
    this.getApiPurchasingSupplierNameApi();
    this.form.purchasingPlanId = this.$route.query.purchasingPlanId;
  },
  destroyed() {
    window.removeEventListener("resize", this.tableHeightChange, true);
  },
  methods: {
    tableHeightChange() {
      this.tableHeight = 0;
      setTimeout(() => {
        this.tableHeight = window.innerHeight - 370; // 表格自适应高度
      }, 100);
    },
    // 处理两位小数
    floatInput(val) {
      let checkPlan = "" + val;
      checkPlan = checkPlan
        .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(/^\./g, "") // 保证第一个为数字而不是.
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      if (checkPlan.indexOf(".") < 0 && checkPlan !== "") {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        checkPlan = parseFloat(checkPlan) + "";
      } else if (checkPlan.indexOf(".") >= 0) {
        checkPlan = checkPlan.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      }
      console.log(checkPlan);
      this.$nextTick(() => (this.form.packagingQty = checkPlan * 1));
      return checkPlan;
    },
    // 日期时间组件
    sDateChange(v) {
      this.$set(this.searchForm, "supplyDate", v);
    },
    // 添加采购单明细/新增
    onAdd() {
      console.log(this.$route.query
        .supplyId
        ? this.$route.query.supplyId
        : this.searchForm.supplyId,this.searchForm.supplyId);
      this.$refs["addPurchaseDetails"].supplyTree = this.supplyTree;
      this.$refs["addPurchaseDetails"].form.supplyId = this.$route.query
        .supplyId
        ? this.$route.query.supplyId
        : this.searchForm.supplyId;
      if (this.$route.query.interId) {
        this.$refs["addPurchaseDetails"].form.interId =
          this.$route.query.interId;
      }
      this.$refs["addPurchaseDetails"].form.supplyName =
        this.$route.query.supplyName; //供应商名称
      this.$refs["addPurchaseDetails"].show();
    },
    // 保存
    onSave() {
      console.log(this.searchForm.supplyDate);
      if (
        this.searchForm.supplyDate != "" &&
        this.searchForm.supplyDate != null &&
        this.searchForm.supplyDate != undefined
      ) {
        this.postApiPurchasingManualSavePoOrderApi();
      } else {
        this.$Message.info("供应日期不能为空");
      }
    },
    // 修改
    onEdit(row) {
      console.log("-----", row);
      this.show = true;
      this.form = this.$cu.deepClone(row);
      this.form.packagingQty = this.$cu.deepClone(row.packagingQty);
        this.form.packagingPrice = this.$cu.deepClone(row.packagingPrice);
      // if (row.specifications == "公斤" || row.specifications == "斤") {
      //   this.weightFlag = true;
      //   this.form.weight = this.$cu.deepClone(row.weight);
      //   console.log("按照规格公斤展示商品重量");
      // } else {
      //   this.weightFlag = false;
      //   this.form.weight = this.$cu.deepClone(row.qty);
      //   this.form.price = this.$cu.deepClone(row.packagingPrice);
      //   console.log("否则展示商品数量");
      // }
    },
    // 修改采购食材确认
    ok() {
      if (this.form.packagingQty == 0) {
        this.$Message.info("采购数量不能为0!");
      } else {
        this.postApiPurchasingUpdatePoOrderDtlApi();
      }
    },
    // 删除
    onDelete(row) {
      this.$cu
        .dialog({
          params: row,
        })
        .then(({ id }) => {
          this.postApiPurchasingDeletePoOrderDtlByIdApi(id);
        });
    },
    // 打印
    // onPrint() {
    //   let newstr = document.getElementById("printContent").innerHTML;
    //   let oldstr = document.body.innerHTML;
    //   document.body.innerHTML = newstr;
    //   window.print();
    //   document.body.innerHTML = oldstr;
    //   return false;
    // },
    // 返回上一页面
    onReturn() {
      window.history.back(); //回退，刷新
    },
    // 采购食材列表-------------------------接口
    postApiPurchasingPoorderdtllistApi() {
      console.log(this.$route.query);
      return new Promise((resolve) => {
        let params = {
          current: this.pages.page,
          size: this.pages.pageSize,
          interId: this.$route.query.interId || 0,
        };
        postApiPurchasingPoorderdtllist(params).then((res) => {
          if (res.retCode == 2000) {
            res.data.records.forEach((element) => {
              // element.weight = element.weight;
              // element.price = element.price;
              element.packagingPrice = element.packagingPrice;
              element.amount = element.amount;
            });
            this.data = res.data.records;
            this.pages.pageTotal = res.data.total;
            resolve();
          }
        });
      });
    },
    // 供应商名称-----------------------接口
    getApiPurchasingSupplierNameApi() {
      return new Promise((resolve) => {
        getApiPurchasingSupplierName().then((res) => {
          if (res.retCode == 2000) {
            this.supplyTree = res.data;
            if (res.data) {
              this.searchForm.supplyId = res.data[0].id;
            }
            resolve();
          }
        });
      });
    },
    // 保存采购单-----------------------接口
    postApiPurchasingManualSavePoOrderApi() {
      return new Promise((resolve) => {
        let params = {
          purchasingPlanId: this.$route.query.purchasingPlanId, //采购计划id
          supplyDate: this.searchForm.supplyDate, //供应时间
          supplyId: this.searchForm.supplyId, //供应商id
        };
        postApiPurchasingManualSavePoOrder(params).then((res) => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.$router.push({
              name: "采购单查看",
              query: {
                id: this.$route.query.purchasingPlanId,
                status:this.$route.query.status,
              },
            });
            resolve();
          }
        });
      });
    },
    // 修改采购单--------------------------接口
    postApiPurchasingUpdatePoOrderDtlApi() {
      return new Promise((resolve) => {
        let params = {
          id: this.form.id,
          // weight: this.form.packagingQty,
          packagingQty:this.form.packagingQty,
        };
        postApiPurchasingUpdatePoOrderDtl(params).then((res) => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.postApiPurchasingPoorderdtllistApi();
            this.show = false;
            resolve();
          }
        });
      });
    },
    // 删除采购单--------------------------接口
    postApiPurchasingDeletePoOrderDtlByIdApi(id) {
      return new Promise((resolve) => {
        postApiPurchasingDeletePoOrderDtlById({ id: id }).then((res) => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.postApiPurchasingPoorderdtllistApi();
            resolve();
          }
        });
      });
    },
  },
  computed: {
    //动态计算金额
    sum() {
      // if (this.weightFlag) {
      //   this.amountSum = this.form.weight;
      // } else {
      //   this.amountSum = this.form.packagingQty;
      // }
      this.amountSum = this.form.packagingQty;
      let amount = parseFloat(this.form.packagingPrice) * parseFloat(this.amountSum);
      return parseFloat(amount).toFixed(2);
    },
  },
};
</script>

<style lang="less" scoped>
.contentBox {
  height: 60px;
  display: flex;
  &-itemRightBox {
    height: 40px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #1e6fff;
    .dl {
      display: flex;
      // justify-content: center;
      justify-content: flex-start;
      align-items: center;
    }
  }
}
</style>
